package com.ls.lserp.modules.produce.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.excel.ExportExcel;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.order.entity.BigcargoOrder;
import com.ls.lserp.modules.order.entity.ChangeMaterial;
import com.ls.lserp.modules.order.entity.OrderMateriel;
import com.ls.lserp.modules.order.entity.SizeColorQuantity;
import com.ls.lserp.modules.order.entity.StyleFeedBack;
import com.ls.lserp.modules.order.entity.StyleOptionEntity;
import com.ls.lserp.modules.produce.entity.ProduceLicense;
import com.ls.lserp.modules.produce.entity.ProduceLoss;
import com.ls.lserp.modules.produce.entity.ProduceNotice;
import com.ls.lserp.modules.produce.service.ProduceLicenseService;
import com.ls.lserp.modules.produce.service.ProduceLossService;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/produce/loss/")
public class ProduceLossController extends BaseController {

	
	@Autowired
	private ProduceLossService produceLossService;
	
	private SXSSFWorkbook tsy = new SXSSFWorkbook ();
	@Autowired
	Configuration freemarkerConfiguration;
	
	/**
	 * 采购预付款一览画面
	 * 
	 * 
	 * @return
	 */
	@RequestMapping(value = { "" })
	public String produceLoss(Model model) {
		return "modules/produce/produceLoss";

	}
	
	/**
	 * 拼接一览画面
	 * @param values 
	 * 
	 * 
	 * @return
	 */
	@RequiresPermissions("produce:license:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(ProduceLoss produceLoss, HttpServletRequest request, HttpServletResponse response,
		Model model, String[] values) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute("listNames", "produceLoss");
		// 画面取得的检索项目
		String contractNo = produceLoss.getContractNo();
		String orderNo = produceLoss.getOrderNo();
		String styleNo = produceLoss.getStyleNo();
		String materialCode = produceLoss.getMaterialCode();
		String dateStart = produceLoss.getDateStart();
		String dateEnd = produceLoss.getDateEnd();
		// 拼接字符串供分页使用
		String searchParam = "&contractNo=" + contractNo+"&orderNo="+ orderNo+"&styleNo="+ styleNo+"&materialCode="+ materialCode+"&dateStart="+ dateStart+"&dateEnd="+ dateEnd;
		//放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam);
		// 查询一览页面数据
		Page<ProduceLoss> page = produceLossService.findList(new Page<ProduceLoss>(request, response),
				produceLoss);
		// 读取文件生成字符串
		String strUri = request.getContextPath() + Global.getAdminPath();
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("lossList", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		map.put("springMacroRequestContext", new RequestContext (request));
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("produceLossList.ftl"), map);
		listMap.put("produceLoss", strHtml);
		listMap.put("page", page.getHtml());
		// ajax返回结果
		return renderString(response, listMap);
	}
	
	/**
     * 导出换片明细数据
     *
     * @param response
     * @param styleOptionEntity
     * @return
     */
    @RequiresPermissions("produce:license:view")
    @RequestMapping(value = "exportFile")
    public String exportFile(ProduceLoss produceLoss, HttpServletResponse response) {
        try {
            SXSSFWorkbook wb = new SXSSFWorkbook ();
            List<ProduceLoss> produceLossList = produceLossService.findList (produceLoss);

            // custom_msg04 :定制项目
            new ExportExcel ("换片", wb, "换片明细", ProduceLoss.class, 2).setDataList (produceLossList);
            tsy = wb;
            return renderString (response,"true");
        } catch (Exception e) {
            // 记录日志
            logger.error (e.getMessage (), e);
        }

        // 提示错误信息
        return renderString (response, AjaxDone.error (getText ("System_error_please_contact_your_administrator")));

    }
    
    /**
     * Excel下载
     *
     * @param response
     * @return
     * @throws Exception
     */
    @RequiresPermissions("produce:license:view")
    @RequestMapping(value = {"makeExportFile"})
    public void makeExportFile(String contractNo,HttpServletResponse response, HttpServletRequest request)
            throws Exception {
    	String fileName = "换片明细.xlsx";
        response.reset ();
        response.setContentType ("application/octet-stream; charset=utf-8");
        response.setCharacterEncoding ("UTF-8");
        response.setHeader ("Content-Disposition", "attachment; filename=" + new String (fileName.getBytes (), "ISO-8859-1"));
        tsy.write (response.getOutputStream ());
    }


}
